
/*
 * Binds a TinyMCE widget to <textarea> elements.
 */
angular.module('book').directive('uiTinymce', ['ui.config', function (uiConfig) {
  uiConfig.tinymce = uiConfig.tinymce || {};
  return {
    require: 'ngModel',
    link: function (scope, elm, attrs, ngModel) {
      var expression,
        options = {
          // Update model on button click
          onchange_callback: function (inst) {
            if (inst.isDirty()) {
              inst.save();
              ngModel.$setViewValue(elm.val());
              if (!scope.$$phase)
                scope.$apply();
            }
          },
          // Update model on keypress
          handle_event_callback: function (e) {
            if (this.isDirty()) {
              this.save();
              ngModel.$setViewValue(elm.val());
              if (!scope.$$phase)
                scope.$apply();
            }
            return true; // Continue handling
          },
          // Update model when calling setContent (such as from the source editor popup)
          setup: function (ed) {
            ed.onSetContent.add(function (ed, o) {
              if (ed.isDirty()) {
                ed.save();
                ngModel.$setViewValue(elm.val());
                if (!scope.$$phase)
                  scope.$apply();
              }
            });
          }
        };
      if (attrs.uiTinymce) {
        expression = scope.$eval(attrs.uiTinymce);
      } else {
        expression = {};
      }
      angular.extend(options, uiConfig.tinymce, expression);
      setTimeout(function () {
        elm.tinymce(options);
      });
    }
  };
}]);


angular.module('book').constant('uiDateConfig', {})

angular.module('book').directive('uiDate', ['uiDateConfig', '$timeout', function (uiDateConfig, $timeout) {
  'use strict';
  var options;
  options = {};
  angular.extend(options, uiDateConfig);
  return {
    require:'?ngModel',
    link:function (scope, element, attrs, controller) {
      var getOptions = function () {
        return angular.extend({}, uiDateConfig, scope.$eval(attrs.uiDate));
      };
      var initDateWidget = function () {
        var opts = getOptions();

        // If we have a controller (i.e. ngModelController) then wire it up
        if (controller) {
          // Override ngModelController's $setViewValue
          // so that we can ensure that a Date object is being pass down the $parsers
          // This is to handle the case where the user types directly into the input box
          var _$setViewValue = controller.$setViewValue;
          var settingValue = false;
          controller.$setViewValue = function () {
            if ( !settingValue ) {
              settingValue = true;
              element.datepicker("setDate", element.datepicker("getDate"));
              _$setViewValue.call(controller, element.datepicker("getDate"));
              $timeout(function() {settingValue = false;});
            }
          };

          // Set the view value in a $apply block when users selects
          // (calling directive user's function too if provided)
          var _onSelect = opts.onSelect || angular.noop;
          opts.onSelect = function (value, picker) {
            scope.$apply(function() {
              controller.$setViewValue(value);
              _onSelect(value, picker);
              element.blur();
            });
          };

          // Don't show if we are already setting the value in $setViewValue()
          // (calling directive user's function too if provided)
          var _beforeShow = opts.beforeShow || angular.noop;
          opts.beforeShow = function(input, inst) {
            return !settingValue && _beforeShow(input, inst);
          };

          // Update the date picker when the model changes
          controller.$render = function () {
            var date = controller.$viewValue;
            if ( angular.isDefined(date) && date !== null && !angular.isDate(date) ) {
              throw new Error('ng-Model value must be a Date object - currently it is a ' + typeof date + ' - use ui-date-format to convert it from a string');
            }
            element.datepicker("setDate", date);
          };
        }
        // If we don't destroy the old one it doesn't update properly when the config changes
        element.datepicker('destroy');
        // Create the new datepicker widget
        element.datepicker(opts);
        if ( controller ) {
          // Force a render to override whatever is in the input text box
          controller.$render();
        }
      };
      // Watch for changes to the directives options
      scope.$watch(getOptions, initDateWidget, true);
    }
  };
}
])

angular.module('book').constant('uiDateFormatConfig', '')

angular.module('book').directive('uiDateFormat', ['uiDateFormatConfig', function(uiDateFormatConfig) {
  var directive = {
    require:'ngModel',
    link: function(scope, element, attrs, modelCtrl) {
      var dateFormat = attrs.uiDateFormat || uiDateFormatConfig;
      if ( dateFormat ) {
        // Use the datepicker with the attribute value as the dateFormat string to convert to and from a string
        modelCtrl.$formatters.push(function(value) {
          if (angular.isString(value) ) {
            return jQuery.datepicker.parseDate(dateFormat, value);
          }
          return null;
        });
        modelCtrl.$parsers.push(function(value){
          if (value) {
            return jQuery.datepicker.formatDate(dateFormat, value);
          }
          return null;
        });
      } else {
        // Default to ISO formatting
        modelCtrl.$formatters.push(function(value) {
          if (angular.isString(value) ) {
            return new Date(value);
          }
          return null;
        });
        modelCtrl.$parsers.push(function(value){
          if (value) {
            return value.toISOString();
          }
          return null;
        });
      }
    }
  };
  return directive;
}]);


/**
 * Wraps the
 * @param text {string} haystack to search through
 * @param search {string} needle to search for
 * @param [caseSensitive] {boolean} optional boolean to use case-sensitive searching
 */
demoApp.filter('highlight', function () {
  return function (text, search, caseSensitive) {
    if (search || angular.isNumber(search)) {
      text = text.toString();
      search = search.toString();
      if (caseSensitive) {
        return text.split(search).join('<span class="ui-match">' + search + '</span>');
      } else {
        return text.replace(new RegExp(search, 'gi'), '<span class="ui-match">$&</span>');
      }
    } else {
      return text;
    }
  };
});



/*
 * Defines the ui-if tag. This removes/adds an element from the dom depending on a condition
 * Originally created by @tigbro, for the @jquery-mobile-angular-adapter
 * https://github.com/tigbro/jquery-mobile-angular-adapter
 */
demoApp.directive('uiIf', [function () {
  return {
    transclude: 'element',
    priority: 1000,
    terminal: true,
    restrict: 'A',
    compile: function (element, attr, transclude) {
      return function (scope, element, attr) {

        var childElement;
        var childScope;
 
        scope.$watch(attr['uiIf'], function (newValue) {
          if (childElement) {
            childElement.remove();
            childElement = undefined;
          }
          if (childScope) {
            childScope.$destroy();
            childScope = undefined;
          }

          if (newValue) {
            childScope = scope.$new();
            transclude(childScope, function (clone) {
              childElement = clone;
              element.after(clone);
            });
          }
        });
      };
    }
  };
}]);

  
demoApp.directive('fab', function() {
    return {
        // can be in-lined or async loaded by xhr
        // or inlined as JS string (using template property)
        restrict: "E",
        templateUrl: 'fabTest.html',
        transclude: true,
        scope: {
          title: "@"
        },
       /* template:'<div>eee{{title}}</div>',*/
        link: function (scope, element, attrs) {
         /* scope.model = attrs.fab*/
        }
    };
});


//Inspiration from http://jsfiddle.net/vojtajina/XuhzP/64/
demoApp.directive('inlineEdit', function() {
    return {
        restrict: 'E',
        // can be in-lined or async loaded by xhr
        // or inlined as JS string (using template property)
        templateUrl: 'componentTpl.html',
        scope: {
            model: '=',
            owner: '=',
            ownerdisplayname: '=',
            users: '=',
            priorities: '=',
            update: '&',
            remove: '&',          
            cancel: '&'          
        },
       
        link: function (scope, element, attrs) {
          console.log ("owner....", scope.users, scope.owner, scope.ownerdisplayname)


        /*  for (var i = 0; i < scope.users.length; i++) {
            
            if (scope.users[i].id == scope.owner)
            {
              scope.selectedOwner = scope.users[i]
            }
          };*/
          scope.sourceValue = scope.model;

            if (scope.model.title === "") {
              console.log ("::::>")
              scope.editMode = true;
            }
          
          // Set the default Owner 
          scope.$watch(scope.users, function (newValue) {
              if (scope.users != undefined)
              {
                for(var i = 0; i < scope.users.length; i++)
                {
                  if (scope.users[i].id == scope.owner)
                  {
                    scope.selectedOwner = scope.users[i]
                  }
                }
              }

            });

          // Set the default Owner 
          scope.$watch(scope.priorities, function (newValue) {
              if (scope.priorities != undefined)
              {
                for(var i = 0; i < scope.priorities.length; i++)
                {
                  if (scope.priorities[i].index == scope.model.priority)
                  {
                    scope.model.priority = scope.priorities[i]
                  }
                }
              }

            });



          scope.getOwner = function (index) {

            //model.ownerId = user
            scope.owner = scope.selectedOwner.id;
            scope.ownerdisplayname = scope.selectedOwner.displayedName;


            console.log("getOwner", scope, scope.selectedOwner, scope.users[index])
          }

          scope.setPriority = function (index) {

            //model.ownerId = user
            


            console.log("getOwner", scope, scope.selectedOwner, scope.users[index])
          }


          scope.getPriorityClass = function (priority){
            switch (priority)
            {
              case 1:
                return "zero"
                break;

              case 2:
                return "one"
                break;

              case 3:
                return "two"
                break;
              
              case 4:
                return "three"
                break;

              case 5:
                return "four"
                break;

              
            }
              
          }


        }

    };
});

/*
demoApp.directive('cancel', function() {
    return function(scope, elm, attrs) {
        elm.bind('click', function(e) {
            console.log ("CANCELED")
            scope.setNewData();
        });
    };
});    
*/

demoApp.directive('ngEnter', function() {
    return function(scope, elm, attrs) {
        elm.bind('keypress', function(e) {
            if (e.charCode === 13) scope.$apply(attrs.ngEnter);
        });
    };
});    

/*
function Controller($scope) {
    $scope.items = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
}
*/